import { defineStore } from "pinia";
import { ref, watch } from "vue";
import { signin } from "@/views/LiveNew/LiveNewApi";
import type { PlayerStore } from "@/store/usePlayer";
import { LiveDataStore } from "@/views/LiveNew/stores/LiveDataStore";
import { closeToast, showToast } from "vant";
import { showLoadingToast } from "vant";
export const useSignInStore = defineStore("signIn", () => {
  const isVisible = ref(false);
  const loading = ref(false);
  const setIsVisible = (value: boolean) => {
    isVisible.value = value;
  };
  const handleSignin = async (liveDataStore: LiveDataStore) => {
    loading.value = true;
    try {
      showLoadingToast({
        message: "签到中...",
        duration: 0
      });
      const data = await signin(liveDataStore.roomParams);
      liveDataStore.fetchRoomWatchData();
      if (data) {
        showToast({
          message: "签到成功",
          duration: 2000
        });
        setIsVisible(false);
      }
    } catch (error) {
      closeToast();
    } finally {
      loading.value = false;
    }
  };
  const initWatcher = (
    liveDataStore: LiveDataStore,
    playerStore: PlayerStore
  ) => {
    const { roomData, roomWatchData } = liveDataStore;

    // 如果未配置签到或已签到，则不进行监听
    if (roomData.sign.openSignIn !== 1) {
      return;
    }

    watch(
      () => playerStore.realProgress,
      (newProgress, oldProgress) => {
        if (!newProgress) return;

        const newTime = Math.floor(newProgress);
        const oldTime = Math.floor(oldProgress);
        // 签到时间
        const checkList = [
          roomWatchData.sign1st,
          roomWatchData.sign2nd,
          roomWatchData.sign3rd
        ];
        const timeList = roomData.sign.signInRule.split(",").map(Number);
        checkList.forEach((item, index) => {
          if (!item) {
            // 如果未签到
            if (newTime === timeList[index] * 60 && newTime !== oldTime) {
              setIsVisible(true);
            }
          }
        });
      }
    );
  };
  return {
    isVisible,
    setIsVisible,
    handleSignin,
    loading,
    initWatcher
  };
});

export type SignInStore = ReturnType<typeof useSignInStore>;
